package pl.edu.agh.agents.gui;

import java.awt.Color;
import java.awt.Point;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pl.edu.agh.agents.agent.Agent;
import pl.edu.agh.agents.agent.AgentStrategy;
import pl.edu.agh.agents.agent.AutonomousAgent;
import pl.edu.agh.agents.agent.ControlledAgent;
import pl.edu.agh.agents.state.State;
import pl.edu.agh.agents.xml.XMLConfiguration;
import pl.edu.agh.agents.xml.XMLState;

import com.thoughtworks.xstream.XStream;

public class GraphSaver {
	private static GraphSaver instance = new GraphSaver();

	private GraphSaver() {}

	public static GraphSaver getInstance() {
		return instance;
	}

	public void saveGraphToFile(String filename, List<State> states, List<Point> points, List<Agent> agents, Map<Agent, Color> agentColors) {
		PrintWriter out = null;

		try {
			out = new PrintWriter(new FileWriter(filename));

			List<XMLState> xmlStates = new ArrayList<XMLState>();

			for (State state : states) {
				int ID = state.getID();
				XMLState xmlState = new XMLState(ID, points.get(ID).x, points.get(ID).y, state.isSink(), state.getEnteringProb());

				for (State neighbor : state.getNeighbors()) {
					xmlState.addNeighbor(neighbor.getID());
				}
				xmlStates.add(xmlState);
			}

			XStream xstream = new XStream();
			Class<?>[] classes = { Agent.class, AutonomousAgent.class, ControlledAgent.class, XMLState.class, AgentStrategy.class, XMLConfiguration.class };
			xstream.processAnnotations(classes);
			xstream.setMode(XStream.NO_REFERENCES);

			Map<Integer, Color> agentIDColors = new HashMap<Integer, Color>();
			for (Agent agent : agentColors.keySet()) {
				agentIDColors.put(agent.getID(), agentColors.get(agent));
			}
			XMLConfiguration conf = new XMLConfiguration(xmlStates, agents, agentIDColors);
			xstream.toXML(conf, out);
		}
		catch (Exception ex) {
			System.err.println(ex.getMessage());
		}
		finally {
			if (out != null) {
				out.close();			
				System.out.println("Configuration saved succesfully");
			}
		}
	}

}